package com.hejia.bulbul.scheduler;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.entity.Fund;
import com.hejia.alauda.service.FundService;
import com.hejia.alauda.utils.IFundUtil;

/**
 * 
 * 爱基金基金数据刷新作业
 *
 *
 * Created by showone on 2015 上午10:09:57.
 *
 * @Copyright: 2015 www.hejiajinrong.com All rights reserved.
 */
public class FundScheduler {

	private static final Log Logger = LogFactory.getLog(FundScheduler.class);

	@Resource
	private FundService fundService;

	// [秒] [分] [小时] [日] [月] [周] [年]
	@Scheduled(cron = "0 30 * * * ?")
	@Async("executor")
	public void flashData() {

		Logger.info("爱基金基金数据刷新");
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar ca = Calendar.getInstance();
			String today = sdf.format(ca.getTime());
			int hour = ca.get(Calendar.HOUR_OF_DAY);
			ca.add(Calendar.DATE, -1);
			String yestoday = sdf.format(ca.getTime());

			boolean flag = false;// 是否刷新标志

			List<Fund> list = fundService.findAllFund(null).getList();
			for (int i = 0; list != null && i < list.size(); i++) {
				Fund fund = list.get(i);
				String releaseTime = sdf.format(fund.getReleaseTime());
				if (hour >= 17 && !releaseTime.equals(today)) {
					flag = true;
					break;
				} else if (hour < 17 && !releaseTime.equals(yestoday)) {
					flag = true;
					break;
				}
			}

			/*
			 * 数据已经是最新数据则退出
			 */
			if (!flag) {
				return;
			}

			JSONArray array = IFundUtil.fundData();
			for (int i = 0; array != null && i < array.size(); i++) {
				JSONObject data = array.getJSONObject(i);
				Fund fund = fundService.getFundByFundcode(data
						.getString("fundCode"));
				fund.setReleaseTime(sdf.parse(data.getString("fundDate")));
				fund.setAccrual(BigDecimal.valueOf(Double.parseDouble(data
						.getString("fundIncome"))));
				fund.setFundManager(data.getString("fundManager"));
				fund.setMinAmount(BigDecimal.valueOf(Long.parseLong(data
						.getString("minBidsAmountByIndi"))));
				fund.setOuttime(data.getIntValue("outtime"));
				fund.setSaleCompany(data.getString("saleCompany"));
				fund.setScale(BigDecimal.valueOf(Double.parseDouble(data
						.getString("scale"))));
				fund.setSalestate(data.getString("sgstat"));
				fund.setType(data.getString("type"));
				fund.setAnnualizedReturn(BigDecimal.valueOf(Double
						.parseDouble(data.getString("yield"))));
				fund.setBuyCount(Integer.parseInt(data.getString("buyCount")));
				fund.setCreateDay(data.getString("createDay"));
				fundService.modifyFund(fund);
			}
		} catch (Exception e) {
			Logger.error(e.toString(), e);
		}
	}
}
